package me.zhengjie.modules.transfer.factory.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.account.domain.AccountAc50;
import me.zhengjie.modules.account.mapper.AccountCommonMapper;
import me.zhengjie.modules.account.service.AccountAa02Service;
import me.zhengjie.modules.account.service.AccountAc50Service;
import me.zhengjie.modules.account.service.AccountAc51Service;
import me.zhengjie.modules.sequence.domain.Sequence;
import me.zhengjie.modules.sequence.service.SequenceService;
import me.zhengjie.modules.transfer.domain.*;
import me.zhengjie.modules.transfer.factory.service.*;
import me.zhengjie.modules.transfer.factory.vo.*;
import me.zhengjie.modules.transfer.service.*;
import me.zhengjie.tool.*;
import me.zhengjie.vo.Constant;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 企业转城乡
 */
@Data
@Service
@RequiredArgsConstructor
public class TransferInformationIc74ServiceImpl implements TransferInformationIc74Service {



    private final TransferInformationService transferInformationService;
    private final TransferPersonService transferPerson;
    private final TransOutDealService transOutDealService;
    private final TransCheckService transCheckService;
    private final AccountAc50Service accountAc50Service;
    private final AccountAc51Service accountAc51Service;
    private final AccountCommonMapper accountCommonMapper;
    private final TransferIc74Service transferIc74Service;
    private final TransferIc75Service transferIc75Service;
    private final SequenceService sequenceService;
    private final AccountAa02Service accountAa02Service;

    private final TransferProcessService transferProcessService;


    /**
     * 人员编号
     */
    protected String aac001;

    /**
     * 转出人员编号
     */
    protected String aac319;

    /**
     * 险种类型
     */
    protected String aae140;

    /**
     * 对方险种
     */
    protected String aae241;

    /**
     * 转移数据来源
     */
    protected String aac306;

    /**
     * 上传方经办人
     */
    protected String aae736;

    /**
     * 上传方经办时间
     */
    protected String aae739;

    /**
     * 联网下载标志
     */
    protected String aae732;
    /**
     * 业务环节
     */
    protected String aae803;

    /**
     * 业务环节状态
     */
    protected String aae158;

    /**
     * 户籍地址
     */
    protected String aac010;

    /**
     * 业务类型编码
     */
    protected String aaa121;
    /**
     * 人员信息
     */
    protected TransferPersonInfo transferPersonInfo;


    /**
     * 转移制度方向
     */
    protected String aic113;

    /**
     * 联系函编号
     */
    protected String aae270;

    /**
     * 银行类别
     */
    protected String aaf200;
    /**
     * 地方银行类别
     */
    protected String aaf216;
    /**
     * 地方银行类别名称
     */
    protected String aaf217;
    /**
     * 对方行政区划
     */
    protected String aab299;

    /**
     * 首次参保地缴费时间
     */
    protected String aab305;

    /**
     * 信息表主键id
     */
    protected String infoKey;

    /**
     * 信息表明细id
     */
    protected String detailsKey;

    /**
     * 信息表其他表id
     */
    protected String othersKey;

    /**
     * 转移基金金额
     */
    protected BigDecimal money;

    /**
     * 被确认标志（指信息表是否已经生成缴费或个人账户信息）
     */
    protected String aae733;

    /**
     * 信息表
     */
    protected InformationInfo informationInfo;

    /**
     * 信息表附表
     */
    protected List<InformationDetailInfo> informationDetailInfos = new ArrayList<>();

    /**
     * 信息表其他附表
     */
    protected List<InformationOtherInfo> informationOtherInfos = new ArrayList<>();

    /**
     * 转入转移基金信息
     */
    protected List<MyMap> funds = new ArrayList<>();

    /**
     * 是否跨省转移
     */
    protected boolean transProvincal;


    /**
     * 是否是信息表特权修改
     */
    protected String transModifyInfo;

    /**
     * 是否是历史补录
     */
    protected String transConanctInfo;

    /**
     * 本地缴费记录
     */
    protected List<Map> paymentList;

    /**
     * 是否是说明
     */
    protected String aae013;

    /**
     * 业务日志号
     */
    protected String aaz002;

    @Override
    public Map transOutInfo(MyMap map) {

        this.aac306=Constant.AAC306_1_BD;
        List<Map> paymentList = (List<Map>) map.get("paymentList");
        NPETool.isEmptyThrowException(paymentList, "缴费明细");

        String aac001 = map.getAsString("aac001");
        NPETool.isEmptyThrowException(aac001, "人员编号");
        NPETool.isEmptyThrowException(map.getAsString("aic113"), "转移制度方向");

        MyMap myMap = transferPerson.xxbAae140Aae241(map.getAsString("aic113"));
         aae140 = myMap.getAsString("aae140");
         aae241 = myMap.getAsString("aae241");
        NPETool.isEmptyThrowException(aae140, "险种类型");
        NPETool.isEmptyThrowException(aae140, "转出险种类型");


        this.aaz002=map.getAsString("aaz002");

        //1、获取人员基本信息
        MyMap transferPerson1 = transferPerson.getTransferPerson(aac001, aae140);

        //初始化信息表信息
        TransferInformationIc74(map);

        map.put("aac306", this.aac306);
        //2、组装人员信息
        transferPersonInfoCreate(transferPerson1, map);

        //3、转出通用校验
        transferInformationService.transferOutCheck(aac001, aae140, aae241, aac306, aic113);
        //4、创建信息表
        transferOut();
        //5、信息表规则校验
        transferInCheck();
        //6、保存信息表
        saveInformation();


        map.put("bae038","IC74");
        //7、保存流程信息
        transferProcessService.createProcessTransfer(map);

        return transferPerson1;
    }

    @Override
    public Map informationPreview(MyMap map) {
        this.aac306=Constant.AAC306_1_BD;

        NPETool.isEmptyThrowException(map.get("paymentListXXB"), "缴费明细");

        String aac001 = map.getAsString("aac001");
        NPETool.isEmptyThrowException(aac001, "人员编号");
        NPETool.isEmptyThrowException(map.getAsString("aic113"), "转移制度方向");

        MyMap myMap = transferPerson.xxbAae140Aae241(map.getAsString("aic113"));
         aae140 = myMap.getAsString("aae140");
         aae241 = myMap.getAsString("aae241");
        NPETool.isEmptyThrowException(aae140, "险种类型");
        NPETool.isEmptyThrowException(aae140, "转出险种类型");


        List<Map> ac50s = (List<Map>) map.get("ac50");
        List<Map> ac51s = (List<Map>) map.get("ac51");
        List<Map> ac52s = (List<Map>) map.get("ac52");



        //1、获取人员基本信息
        MyMap transferPerson1 = transferPerson.getTransferPerson(aac001, aae140);

        //初始化信息表信息
        TransferInformationIc74(map);

        map.put("aac306", this.aac306);
        //2、组装人员信息
        transferPersonInfoCreate(transferPerson1,map);

        //3、转出通用校验
        transferInformationService.transferOutCheck(aac001, aae140, aae241, aac306, aic113);
        //5、预览生成信息表
        transferOutPrivew(ac50s, ac51s, ac52s);
        //6、信息表规则校验
        // transferInCheck();


        Map infromationMap = new HashMap();


        infromationMap.put("information", informationInfo);
        infromationMap.put("informationDetail", informationDetailInfos);
        infromationMap.put("informationOtherInfos", informationOtherInfos);


        System.out.println(JSON.toJSONString(infromationMap));
        return infromationMap;
    }

    @Override
    public Map transOutRevoke(String aaz002) {
        HashMap map = new HashMap<>();
        map.put("aaz002",aaz002);
        transferIc74Service.removeByMap(map);
        transferIc75Service.removeByMap(map);
        return null;
    }




    public void TransferInformationIc74(MyMap myMap) {

        this.aac001 = myMap.getAsString("aac001");
        this.aac319 = myMap.getAsString("aac319");
        this.aae736 = myMap.getAsString("aae736");
        this.aae739 = myMap.getAsString("aae739");
        this.aae732 = myMap.getAsString("aae732");
        this.aac010 = myMap.getAsString("aac010");


        this.aic113 = myMap.getAsString("aic113");
        this.aae270 = myMap.getAsString("aae270");
        this.aac319 = myMap.getAsString("aac319");
        this.aab305 = myMap.getAsString("aab305");
        this.paymentList = new ArrayList<>();

        if (!ValidateUtil.isEmpty(myMap.get("paymentList"))) {
            paymentList.addAll((List<Map>) myMap.get("paymentList"));
        }
        if (Constant.AAC306_2_YD.equals(this.aac306)) {
            if (!ValidateUtil.isEmpty(myMap.getAsString("fund")) && !"[]".equals(myMap.getAsString("fund"))) {
                List<MyMap> funds_1 = ListUtil.list2MyMapList(JSON.parseArray(myMap.getAsString("fund"), List.class));
                this.funds.addAll(funds_1);
                this.aae733 = Constant.AAE733_1_S;
            } else {
                this.aae733 = Constant.AAE733_0_F;
                if (!ValidateUtil.isEmpty(myMap.get("info"))) {
                    MyMap infoMyMap = MyMap.convertToMap(myMap.getAsString("info"));
                    //如果只转视同，则默认aae733为1，这样才会写入ac08
                    if (!ValidateUtil.isEmpty(infoMyMap.get("aic102"))) {
                        if (BigDecimal.ZERO.compareTo(infoMyMap.getAsBigDecimal("aic102")) == 0) {
                            this.aae733 = Constant.AAE733_1_S;
                        }
                    }
                }
            }
            //外部参数干预 确认标志 （特权维护直接确认）
            if (!ValidateUtil.isEmpty(myMap.getAsString("aae733"))) {
                this.aae733 = myMap.getAsString("aae733");

            }

        } else {
            Map orginfoin = (Map) myMap.get("orginfoin");
            if (!ValidateUtil.isEmpty(orginfoin)) {
                this.aaf216 = (String) orginfoin.get("aaf216");
                this.aaf200 = (String) orginfoin.get("aaf200");
                this.aaf217 = (String) orginfoin.get("aaf217");
                this.aae270 = (String) orginfoin.get("aae270");
                //转出 对方联系函aab301 是转入地行政区划
                this.aab299 = (String) orginfoin.get("aab301");

            }
        }


        this.aae803 = Constant.AAE803_T0802_CZZGYLBXZRCXJMYLBXXXB;
        if (!ValidateUtil.isEmpty(myMap.getAsString("transModifyInfo"))) {
            this.transModifyInfo = "1";
        }

        if (!ValidateUtil.isEmpty(myMap.getAsString("transConanctInfo"))) {
            this.transConanctInfo = "1";
        }

        if (!ValidateUtil.isEmpty(myMap.getAsString("aae013"))) {
            this.aae013 = myMap.getAsString("aae013");
        }

        if (Constant.AAC306_2_YD.equals(this.aac306)) {
            initInInformation(myMap);
        }
    }

    //转入初始化信息表
    public void initInInformation(MyMap myMap) {

        MyMap info = JSONObject.parseObject(myMap.getAsString("info"), MyMap.class);
        NPETool.isEmptyThrowException(info, "信息表信息");

        String aab301 = info.getAsString("aab301");
        NPETool.isEmptyThrowException(aab301, "转出地行政区划");

        String aab299 = info.getAsString("aab299");
        NPETool.isEmptyThrowException(aab299, "转入地行政区划");

        String aac006 = info.getAsString("aac006");
        NPETool.isEmptyThrowException(aac006, "出生日期");

        if (aab301.substring(0, 2).equals(aab299.substring(0, 2))) {
            this.transProvincal = false;
            //省内转移 直接确认 生成缴费和账户
            this.aae733 = Constant.AAE733_1_S;
        } else {
            this.transProvincal = true;
        }
        this.aac319 = info.getAsString("aac319");

        List<MyMap> detailList = ListUtil.list2MyMapList(JSONObject.parseObject(myMap.getAsString("infoDetails"), List.class));

        info.put("aab300", "");//转出地社保经办机构 todo  转出机构信息
        info.put("aaa146", "");//转入地社保经办机构
        this.informationInfo = new Ic90Info(info);

        InformationDetailInfo informationDetailInfo;
        int aaz751 = 0;
        String aae013 = "";
        for (MyMap map : detailList) {
            map.put("aac001", this.aac001);
            map.put("aaz751", aaz751);
            aae013 = map.getAsString("aae013");
            if (!ValidateUtil.isEmpty(aae013) && (aae013.contains("null") || aae013.contains("NULL"))) {
                aae013 = aae013.replaceAll("null", "").replaceAll("NULL", "");
                map.put("aae013", aae013);
            }
            informationDetailInfo = new Ic91Info(map);
            this.informationDetailInfos.add(informationDetailInfo);
            aaz751++;
        }

    }


    public void transferOut() {
        this.informationInfo = new InformationInfo();//信息表信息
        this.informationDetailInfos = new ArrayList<>();//信息表明细信息
        createInformationOfIc74();
    }


    /**
     * 转出预览生成信息表
     */

    public void transferOutPrivew(List<Map> ac50s, List<Map> ac51s, List<Map> ac52s) {

        this.informationInfo = new InformationInfo();//信息表信息
        this.informationDetailInfos = new ArrayList<>();//信息表明细信息
        this.informationOtherInfos = new ArrayList<>();//附表信息

        createInformationOfIc74Preview(ac50s, ac52s);
    }




        /**
         * 创建信息表
         */
        private void createInformationOfIc74() {

            //后台根据账户类型判断 无需前台传入
            this.aae803 = Constant.AAE803_T0802_CZZGYLBXZRCXJMYLBXXXB;
            QueryWrapper<AccountAc50> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("aaz159", this.transferPersonInfo.getAaz159());
            queryWrapper.eq("aac001", this.transferPersonInfo.getAac001());
            queryWrapper.eq("aac062", Constant.AAC062_1_RYXCB);

            List<Map<String, Object>> ac50s = accountAc50Service.listMaps(queryWrapper);
            // 查询出人员的全部正常缴费记录
            List<Map> ac08List = this.paymentList;

            Collections.sort(ac08List, Comparator.comparing(a -> Integer.valueOf(a.get("aae003") + "")));


            BigDecimal aae030 = new BigDecimal(ac08List.get(0).get("aae003").toString());
            BigDecimal aae031 = new BigDecimal(ac08List.get(ac08List.size() - 1).get("aae003").toString());
            BigDecimal aae199 = BigDecimal.ZERO;

            MyMap myMap;
            for (Map map : ac08List) {
                myMap = new MyMap(map);
                // 处理年度
                map.put("aae001", myMap.getAsString("aae003").substring(0, 4));
                aae199 = aae199.add(myMap.getAsBigDecimal("aae202"));
            }
            BigDecimal aic083 = BigDecimal.ZERO;
            MyMap ac50;
            for (Map map : ac50s) {
                ac50 = new MyMap(map);
                aic083 = aic083.add(ac50.getAsBigDecimal("aae240"));
            }


            Sequence sequence_aae405 = new Sequence();
            sequence_aae405.setName("aae405");
            String aae405=sequenceService.nextSequence(sequence_aae405);

            Sequence sequence_aaz086 = new Sequence();
            sequence_aaz086.setName("aaz086");
            String aaz086=sequenceService.nextSequence(sequence_aaz086);

            Sequence sequence_aaz341 = new Sequence();
            sequence_aaz341.setName("aaz341");
            String aaz341=sequenceService.nextSequence(sequence_aaz341);

            //组装参数
            Ic74Info ic74Info = new Ic74Info();
            ic74Info.setAaz086(BigDecimalUtil.getBigDecimal(aaz086));
            ic74Info.setAaz341(BigDecimalUtil.getBigDecimal(aaz341));
            ic74Info.setAab301(this.transferPersonInfo.getAab359());
            ic74Info.setAab299(this.aab299);
            ic74Info.setAae270(this.aae270);
            ic74Info.setAae405(aae405);
            ic74Info.setAae241(this.aae241);
            ic74Info.setAae140(this.aae140);
            ic74Info.setAac319(this.aac001);
            ic74Info.setAac001(BigDecimalUtil.getBigDecimal(aac001));
            ic74Info.setAac002(this.transferPersonInfo.getAac002());
            ic74Info.setAac003(this.transferPersonInfo.getAac003());
            ic74Info.setAac004(this.transferPersonInfo.getAac004());
            ic74Info.setAac006(this.transferPersonInfo.getAac006());
            ic74Info.setAac010(ValidateUtil.isEmpty(this.aac010) ? this.transferPersonInfo.getAac010() : this.aac010);//户口所在地址:VARCHAR2(300)
            ic74Info.setAaa146(null);
            ic74Info.setAab300(null);
            ic74Info.setAae030(aae030);
            ic74Info.setAae031(aae031);
            ic74Info.setAae199(aae199);
//            ic74Info.setAae062(BigDecimalUtil.getBigDecimal(Sequence.next("aae062")));
            ic74Info.setAae005(null);
            ic74Info.setAic083(aic083);
//            ic74Info.setAad019(BigDecimalUtil.getBigDecimal(Sequence.next("aad019")));
            ic74Info.setAae035(BigDecimalUtil.getBigDecimal(DateUtil.getCurrentTime("yyyyMMdd")));
            ic74Info.setAac306(this.aac306);
            ic74Info.setAaz159(this.transferPersonInfo.getAaz159());
            ic74Info.setAae013("");
            ic74Info.setAaz002(this.aaz002);
            this.informationInfo = ic74Info;
            List<Ic75Info> detailCZCXES = new ArrayList<>();


                List<Ic75Info> detailNeedCZCXES = new ArrayList<>();

                // 汇总数据
                Map<Integer, Map<String, Object>> summary = ac08List.stream().collect(
                        Collectors.groupingBy(
                                entry -> Integer.parseInt(entry.get("aae003").toString().substring(0, 4)),
                                Collectors.collectingAndThen(
                                        Collectors.toList(),
                                        list -> {
                                            int minStart = list.stream()
                                                    .mapToInt(e -> Integer.parseInt(e.get("aae003").toString()))
                                                    .min()
                                                    .orElse(Integer.MAX_VALUE);
                                            int maxEnd = list.stream()
                                                    .mapToInt(e -> Integer.parseInt(e.get("aae003").toString()))
                                                    .max()
                                                    .orElse(Integer.MIN_VALUE);
                                            int totalAmount = list.stream()
                                                    .mapToInt(e -> Integer.parseInt(e.get("aae202").toString()))
                                                    .sum();

                                            Map<String, Object> result = new HashMap<>();
                                            result.put("aae041", minStart);
                                            result.put("aae042", maxEnd);
                                            result.put("aae202", totalAmount);
                                            return result;
                                        }
                                )
                        )
                );

                Integer minyear = summary.keySet().stream().min(Integer::compareTo).orElse(null);
                Integer maxyear = summary.keySet().stream().max(Integer::compareTo).orElse(null);
                Integer nowYear = DateUtil.getYear(new Date());


                //因为考虑到年度中断问题 所以从最小年度遍历到转移当年
                for (int i = minyear; i <= maxyear; i++) {
                    Map<String, Object> ic75Map = summary.get(i);
                    if (ValidateUtil.isEmpty(ic75Map)) {//考虑到存在年度终端的情况
                        Ic75Info ic75Info = new Ic75Info();
                        ic75Info.setAac319(this.aac001);
                        ic75Info.setAaz341(new BigDecimal(aaz341));
                        ic75Info.setAac001(BigDecimalUtil.getBigDecimal(this.aac001));
                        ic75Info.setAae001(BigDecimalUtil.getBigDecimal(i));
                        ic75Info.setAae041(BigDecimalUtil.getBigDecimal(i * 100 + 12));
                        ic75Info.setAae042(BigDecimalUtil.getBigDecimal(i * 100 + 12));
                        ic75Info.setAae202(BigDecimal.ZERO);
                        ic75Info.setAac306(this.aac306);
                        ic75Info.setAaz159(this.transferPersonInfo.getAaz159());
                        ic75Info.setAae013("");
                        ic75Info.setAab301(this.transferPersonInfo.getAab359());
                        detailNeedCZCXES.add(ic75Info);
                    } else {
                        Ic75Info ic75Info = new Ic75Info();
                        ic75Info.setAac319(this.aac001);
                        ic75Info.setAaz341(new BigDecimal(aaz341));
                        ic75Info.setAac001(BigDecimalUtil.getBigDecimal(this.aac001));
                        ic75Info.setAae001(BigDecimalUtil.getBigDecimal(i));
                        ic75Info.setAae041(BigDecimalUtil.getBigDecimal(ic75Map.get("aae041").toString()));
                        ic75Info.setAae042(BigDecimalUtil.getBigDecimal(ic75Map.get("aae042").toString()));
                        ic75Info.setAae202(BigDecimalUtil.getBigDecimal(ic75Map.get("aae202").toString()));
                        ic75Info.setAac306(this.aac306);
                        ic75Info.setAaz159(this.transferPersonInfo.getAaz159());
                        ic75Info.setAae013("");
                        ic75Info.setAab301(this.transferPersonInfo.getAab359());
                        detailNeedCZCXES.add(ic75Info);
                    }


                }


                detailCZCXES.addAll(detailNeedCZCXES);




            Collections.sort(detailCZCXES, Comparator.comparing(a -> a.getAae001().intValue() + ""));

            this.informationDetailInfos.addAll(detailCZCXES);
        }


        /**
         * 创建信息表
         */
        private void createInformationOfIc74Preview(List<Map> ac50s, List<Map> ac52s) {

            NPETool.isEmptyThrowException(ac50s, "个人账户信息");


            List<Map> ac08List = this.paymentList;
            Collections.sort(ac08List, Comparator.comparing(a -> Integer.valueOf(a.get("aae003") + "")));


            BigDecimal aae030 = new BigDecimal(ac08List.get(0).get("aae003").toString());
            BigDecimal aae031 = new BigDecimal(ac08List.get(ac08List.size() - 1).get("aae003").toString());
            BigDecimal aae199 = BigDecimal.ZERO;

            MyMap myMap;
            for (Map map : ac08List) {
                myMap = new MyMap(map);
                // 处理年度
                map.put("aae001", myMap.getAsString("aae003").substring(0, 4));
                aae199 = aae199.add(myMap.getAsBigDecimal("aae202"));
            }
            BigDecimal aic083 = BigDecimal.ZERO;
            MyMap ac50;
            for (Map map : ac50s) {
                ac50 = new MyMap(map);
                aic083 = aic083.add(ac50.getAsBigDecimal("aae240"));
            }


            Sequence sequence_aae405 = new Sequence();
            sequence_aae405.setName("aae405");
            String aae405=sequenceService.nextSequence(sequence_aae405);

            Sequence sequence_aaz086 = new Sequence();
            sequence_aaz086.setName("aaz086");
            String aaz086=sequenceService.nextSequence(sequence_aaz086);

            Sequence sequence_aaz341 = new Sequence();
            sequence_aaz341.setName("aaz341");
            String aaz341=sequenceService.nextSequence(sequence_aaz341);

            //组装参数
            Ic74Info ic74Info = new Ic74Info();
            ic74Info.setAaz086(BigDecimalUtil.getBigDecimal(aaz086));
            ic74Info.setAaz341(BigDecimalUtil.getBigDecimal(aaz341));
            ic74Info.setAab301(this.transferPersonInfo.getAab359());
            ic74Info.setAab299(this.aab299);
            ic74Info.setAae270(this.aae270);
            ic74Info.setAae405(aae405);
            ic74Info.setAae241(this.aae241);
            ic74Info.setAae140(this.aae140);
            ic74Info.setAac319(this.aac001);
            ic74Info.setAac001(BigDecimalUtil.getBigDecimal(aac001));
            ic74Info.setAac002(this.transferPersonInfo.getAac002());
            ic74Info.setAac003(this.transferPersonInfo.getAac003());
            ic74Info.setAac004(this.transferPersonInfo.getAac004());
            ic74Info.setAac006(this.transferPersonInfo.getAac006());
            ic74Info.setAac010(ValidateUtil.isEmpty(this.aac010) ? this.transferPersonInfo.getAac010() : this.aac010);//户口所在地址:VARCHAR2(300)
            ic74Info.setAaa146(null);
            ic74Info.setAab300(null);
            ic74Info.setAae030(aae030);
            ic74Info.setAae031(aae031);
            ic74Info.setAae199(aae199);
//            ic74Info.setAae062(BigDecimalUtil.getBigDecimal(Sequence.next("aae062")));
            ic74Info.setAae005(null);
            ic74Info.setAic083(aic083);
//            ic74Info.setAad019(BigDecimalUtil.getBigDecimal(Sequence.next("aad019")));
            ic74Info.setAae035(BigDecimalUtil.getBigDecimal(DateUtil.getCurrentTime("yyyyMMdd")));
            ic74Info.setAac306(this.aac306);
            ic74Info.setAaz159(this.transferPersonInfo.getAaz159());
            ic74Info.setAae013("");
            ic74Info.setAaz002(this.aaz002);
            this.informationInfo = ic74Info;
            List<Ic75Info> detailCZCXES = new ArrayList<>();


            List<Ic75Info> detailNeedCZCXES = new ArrayList<>();

            // 汇总数据
            Map<Integer, Map<String, Object>> summary = ac08List.stream().collect(
                    Collectors.groupingBy(
                            entry -> Integer.parseInt(entry.get("aae003").toString().substring(0, 4)),
                            Collectors.collectingAndThen(
                                    Collectors.toList(),
                                    list -> {
                                        int minStart = list.stream()
                                                .mapToInt(e -> Integer.parseInt(e.get("aae003").toString()))
                                                .min()
                                                .orElse(Integer.MAX_VALUE);
                                        int maxEnd = list.stream()
                                                .mapToInt(e -> Integer.parseInt(e.get("aae003").toString()))
                                                .max()
                                                .orElse(Integer.MIN_VALUE);
                                        int totalAmount = list.stream()
                                                .mapToInt(e -> Integer.parseInt(e.get("aae202").toString()))
                                                .sum();

                                        Map<String, Object> result = new HashMap<>();
                                        result.put("aae041", minStart);
                                        result.put("aae042", maxEnd);
                                        result.put("aae202", totalAmount);
                                        return result;
                                    }
                            )
                    )
            );

            Integer minyear = summary.keySet().stream().min(Integer::compareTo).orElse(null);
            Integer maxyear = summary.keySet().stream().max(Integer::compareTo).orElse(null);
            Integer nowYear = DateUtil.getYear(new Date());


            //因为考虑到年度中断问题 所以从最小年度遍历到转移当年
            for (int i = minyear; i <= maxyear; i++) {
                Map<String, Object> ic75Map = summary.get(i);
                if (ValidateUtil.isEmpty(ic75Map)) {//考虑到存在年度终端的情况
                    Ic75Info ic75Info = new Ic75Info();
                    ic75Info.setAac319(this.aac001);
                    ic75Info.setAaz341(new BigDecimal(aaz341));
                    ic75Info.setAac001(BigDecimalUtil.getBigDecimal(this.aac001));
                    ic75Info.setAae001(BigDecimalUtil.getBigDecimal(i));
                    ic75Info.setAae041(BigDecimalUtil.getBigDecimal(i * 100 + 12));
                    ic75Info.setAae042(BigDecimalUtil.getBigDecimal(i * 100 + 12));
                    ic75Info.setAae202(BigDecimal.ZERO);
                    ic75Info.setAac306(this.aac306);
                    ic75Info.setAaz159(this.transferPersonInfo.getAaz159());
                    ic75Info.setAae013("");
                    ic75Info.setAab301(this.transferPersonInfo.getAab359());
                    detailNeedCZCXES.add(ic75Info);
                } else {
                    Ic75Info ic75Info = new Ic75Info();
                    ic75Info.setAac319(this.aac001);
                    ic75Info.setAaz341(new BigDecimal(aaz341));
                    ic75Info.setAac001(BigDecimalUtil.getBigDecimal(this.aac001));
                    ic75Info.setAae001(BigDecimalUtil.getBigDecimal(i));
                    ic75Info.setAae041(BigDecimalUtil.getBigDecimal(ic75Map.get("aae041").toString()));
                    ic75Info.setAae042(BigDecimalUtil.getBigDecimal(ic75Map.get("aae042").toString()));
                    ic75Info.setAae202(BigDecimalUtil.getBigDecimal(ic75Map.get("aae202").toString()));
                    ic75Info.setAac306(this.aac306);
                    ic75Info.setAaz159(this.transferPersonInfo.getAaz159());
                    ic75Info.setAae013("");
                    ic75Info.setAab301(this.transferPersonInfo.getAab359());
                    detailNeedCZCXES.add(ic75Info);
                }


            }


            detailCZCXES.addAll(detailNeedCZCXES);

            Collections.sort(detailCZCXES, Comparator.comparing(a -> a.getAae001().intValue() + ""));

            this.informationDetailInfos.addAll(detailCZCXES);
        }


        private Map<Integer, Map<String, Integer>> aggregateData(List<Map<String, Integer>> dataList) {
            // 按年度分组
            Map<Integer, List<Map<String, Integer>>> yearlyData = new TreeMap<>();
            for (Map<String, Integer> data : dataList) {
                int year = data.get("aae001");
                yearlyData.computeIfAbsent(year, k -> new ArrayList<>()).add(data);
            }

            // 处理年度汇总
            Map<Integer, Map<String, Integer>> result = new TreeMap<>();
            Integer previousYear = null;
            int minYear = Collections.min(yearlyData.keySet());

            for (int year = minYear; year <= Collections.max(yearlyData.keySet()); year++) {
                if (!yearlyData.containsKey(year)) {
                    // 年度中断
                    result.put(year, createMap(year, year * 100 + 12, year * 100 + 12, 0));
                    continue;
                }

                List<Map<String, Integer>> yearData = yearlyData.get(year);
                int minStart = Integer.MAX_VALUE;
                int maxEnd = Integer.MIN_VALUE;
                int totalAmount = 0;

                for (Map<String, Integer> data : yearData) {
                    minStart = Math.min(minStart, data.get("aae041"));
                    maxEnd = Math.max(maxEnd, data.get("aae042"));
                    totalAmount += data.get("aae202");
                }

                result.put(year, createMap(year, minStart, maxEnd, totalAmount));

                // 处理年度中断情况
                if (previousYear != null && year > previousYear + 1) {
                    for (int missingYear = previousYear + 1; missingYear < year; missingYear++) {
                        result.put(missingYear, createMap(missingYear, missingYear * 100 + 12, missingYear * 100 + 12, 0));
                    }
                }

                previousYear = year;
            }

            return result;
        }


        private static Map<String, Integer> createMap(int year, int start, int end, int amount) {
            Map<String, Integer> map = new HashMap<>();
            map.put("aae001", year);
            map.put("aae041", start);
            map.put("aae042", end);
            map.put("aae202", amount);
            return map;
        }


    /**
     * 信息表校验
     */
    public void transferInCheck() {



        NPETool.isEmptyThrowException(this.informationInfo, "信息表信息");
        NPETool.isEmptyThrowException(this.informationDetailInfos, "信息表明细信息");

        String aae270new = this.informationInfo.getAae270();
        NPETool.isEmptyThrowException(aae270new, "联系函编号");

        // 3.校验是否已办理转入
        MyMap myMap = new MyMap();
        myMap.put("aae270", aae270new);
        myMap.put("aac001", this.aac001);
        myMap.put("aac306", Constant.AAC306_2_YD);
        if (!"1".equals(this.transModifyInfo) && !("1".equals(this.transConanctInfo))) {
            List<Map> transferProcess = new ArrayList<>();
//                List<Map> transferProcess = RepositoryRegister.transferRepository().queryProcessInfo(myMap);
            if (!ValidateUtil.isEmpty(transferProcess)) {

                for (Map map : transferProcess) {
                    if (Constant.AAE803_T0102_ZYJXXXB.equals(map.get("aae803")) || Constant.AAE803_T0502_ZRDFQDLSZHZ.equals(map.get("aae803"))
                            || Constant.AAE803_T0601_JRTYYLBXCBJFPZHXXB.equals(map.get("aae803")) || Constant.AAE803_T0703_CXJMYLBXZRCZZGYLBXXXB.equals(map.get("aae803"))
                            || Constant.AAE803_T0802_CZZGYLBXZRCXJMYLBXXXB.equals(map.get("aae803")) || Constant.AAE803_T0902_CXJBYLBXKDQZYSPB.equals(map.get("aae803"))
                            || Constant.AAE803_T1102_JGYLBXZYXXB.equals(map.get("aae803")) || Constant.AAE803_T1201_JGSYYLBXCZCTRYZYXXB.equals(map.get("aae803"))
                            || Constant.AAE803_T1302_JGSYYLBXZYNJZYXXB.equals(map.get("aae803"))) {
                        throw new IllegalArgumentException("当前联系函已办理了转入");
                    }
                }
            }
        }



        transCheckService.checkInformationOfStaffToResident(informationInfo, informationDetailInfos);

    }


    /**
     * 组装人员信息
     *
     * @param transferPerson
     * @param map
     */
    void transferPersonInfoCreate(MyMap transferPerson,MyMap map) {
        transferPersonInfo = new TransferPersonInfo();

        /**
         * 首次参保地缴费时间
         */
        this.aab305 = transferPerson.getAsString("aab305");
        /**
         * 单位编号
         */
        transferPersonInfo.setAab001(transferPerson.getAsBigDecimal("aab001"));
        /**
         * 单位名称
         */
        transferPersonInfo.setAab004(transferPerson.getAsString("aab004"));
        /**
         * 人员编号
         */
        ;
        transferPersonInfo.setAac001(transferPerson.getAsBigDecimal("aac001"));
        /**
         * 社会保障号
         */
        transferPersonInfo.setAac002(transferPerson.getAsString("aac002"));
        /**
         * 姓名
         */
        ;
        transferPersonInfo.setAac003(transferPerson.getAsString("aac003"));
        /**
         * 性别
         */
        transferPersonInfo.setAac004(transferPerson.getAsString("aac004"));
        /**
         * 出生日期
         */
        transferPersonInfo.setAac006(transferPerson.getAsBigDecimal("aac006"));
        /**
         * 参加工作日期
         */
        transferPersonInfo.setAac007(transferPerson.getAsBigDecimal("aac007"));
        /**
         * 户口性质（户籍地类别）
         */
        transferPersonInfo.setAac009(transferPerson.getAsString("aac009"));
        /**
         * 户口所在地址
         */
        transferPersonInfo.setAac010(transferPerson.getAsString("aac010"));
        /**
         * 手机号码
         */
        transferPersonInfo.setAac067(transferPerson.getAsString("aac067"));
        /**
         * 农民工标识
         */
        ;
        transferPersonInfo.setAac028(transferPerson.getAsString("aac028"));
        /**
         * 人员参保关系ID
         */
        transferPersonInfo.setAaz159(transferPerson.getAsBigDecimal("aaz159"));
        /**
         * 个人参保日期
         */
        transferPersonInfo.setAac030(transferPerson.getAsBigDecimal("aac030"));
        /**
         * 参保险种
         */
        transferPersonInfo.setAae140(transferPerson.getAsString("aae140"));
        /**
         * 人员账户类别
         */
        transferPersonInfo.setAae473(transferPerson.getAsString("aae473"));
        /**
         * 统筹区
         */
        transferPersonInfo.setAaa027(transferPerson.getAsString("aaa027"));

        /**
         * 参保机构
         */
        transferPersonInfo.setAab359(map.getAsString("aab359"));
        /**
         * 首次参保年月
         */
        transferPersonInfo.setAac049(transferPerson.getAsBigDecimal("aac049"));

        /**
         * 建立账户年月
         */
        transferPersonInfo.setAae206(transferPerson.getAsBigDecimal("aae206"));

        /**
         * 用工形式
         */
        transferPersonInfo.setAac013(transferPerson.getAsString("aac013"));

        this.aab305 = transferPerson.getAsString("aab305");

        Map orginfoin = (Map) map.get("orginfoin");
        if (!ValidateUtil.isEmpty(orginfoin)) {//转入机构信息从联系函获取
            transferPersonInfo.setAab299(orginfoin.get("aab301").toString());
            transferPersonInfo.setAae270(orginfoin.get("aae270").toString());
        }
        transferPersonInfo.setAae011(map.getAsString("aae011"));

    }

    /**
     * 保存
     */

    public Map saveInformation() {

        Map ic74 = BeanUtil.beanToMap(this.informationInfo);
        TransferIc74 transferIc74 = new TransferIc74();
        Sequence sequence_aaz086 = new Sequence();
        sequence_aaz086.setName("aaz086");
        String aaz086 = sequenceService.nextSequence(sequence_aaz086);
        String aae036= DateUtil.getCurrentTime("yyyyMMddHHmmss");

        transferIc74.setAaz086(aaz086);
        transferIc74.setAaz341(ValidateUtil.isEmpty(ic74.get("aaz341")) ? null : ic74.get("aaz341").toString());
        transferIc74.setAab301(ValidateUtil.isEmpty(ic74.get("aab301")) ? null : ic74.get("aab301").toString());
        transferIc74.setAab299(ValidateUtil.isEmpty(ic74.get("aab299")) ? null : ic74.get("aab299").toString());
        transferIc74.setAae270(ValidateUtil.isEmpty(ic74.get("aae270")) ? null : ic74.get("aae270").toString());
        transferIc74.setAae405(ValidateUtil.isEmpty(ic74.get("aae405")) ? null : ic74.get("aae405").toString());
        transferIc74.setAae140(this.aae140);
        transferIc74.setAae241(this.aae241);
        transferIc74.setAac319(ValidateUtil.isEmpty(ic74.get("aac319")) ? null : ic74.get("aac319").toString());
        transferIc74.setAac001(ValidateUtil.isEmpty(ic74.get("aac001")) ? null : ic74.get("aac001").toString());
        transferIc74.setAac002(ValidateUtil.isEmpty(ic74.get("aac002")) ? null : ic74.get("aac002").toString());
        transferIc74.setAac003(ValidateUtil.isEmpty(ic74.get("aac003")) ? null : ic74.get("aac003").toString());
        transferIc74.setAac004(ValidateUtil.isEmpty(ic74.get("aac004")) ? null : ic74.get("aac004").toString());
        transferIc74.setAac006(ValidateUtil.isEmpty(ic74.get("aac006")) ? null : new BigDecimal(ic74.get("aac006").toString()));
        transferIc74.setAac010(ValidateUtil.isEmpty(ic74.get("aac010")) ? null : ic74.get("aac010").toString());
        transferIc74.setAaa146(ValidateUtil.isEmpty(ic74.get("aaa146")) ? null : ic74.get("aaa146").toString());
        transferIc74.setAae030(ValidateUtil.isEmpty(ic74.get("aae030")) ? null : new BigDecimal(ic74.get("aae030").toString()));
        transferIc74.setAae031(ValidateUtil.isEmpty(ic74.get("aae031")) ? null : new BigDecimal(ic74.get("aae031").toString()));
        transferIc74.setAae199(ValidateUtil.isEmpty(ic74.get("aae199")) ? null : new BigDecimal(ic74.get("aae199").toString()));
        transferIc74.setAae733(ValidateUtil.isEmpty(ic74.get("aae733")) ? null : ic74.get("aae733").toString());
        transferIc74.setAae730(ValidateUtil.isEmpty(ic74.get("aae730")) ? null : ic74.get("aae730").toString());
        transferIc74.setAae736(ValidateUtil.isEmpty(ic74.get("aae736")) ? null : ic74.get("aae736").toString());
        transferIc74.setAae739(ValidateUtil.isEmpty(ic74.get("aae739")) ? null : new BigDecimal(ic74.get("aae739").toString()));
        transferIc74.setAae062(ValidateUtil.isEmpty(ic74.get("aae062")) ? null : new BigDecimal(ic74.get("aae062").toString()));
        transferIc74.setAae005(ValidateUtil.isEmpty(ic74.get("aae005")) ? null : ic74.get("aae005").toString());
        transferIc74.setAic083(ValidateUtil.isEmpty(ic74.get("aic083")) ? null : new BigDecimal(ic74.get("aic083").toString()));


        transferIc74.setAad019(ValidateUtil.isEmpty(ic74.get("aad019")) ? null : new BigDecimal(ic74.get("aad019").toString()));
        transferIc74.setAae035(ValidateUtil.isEmpty(ic74.get("aae035")) ? null : new BigDecimal(ic74.get("aae035").toString()));
        transferIc74.setAaa146(ValidateUtil.isEmpty(ic74.get("aaa146")) ? null : ic74.get("aaa146").toString());
        transferIc74.setAab300(ValidateUtil.isEmpty(ic74.get("aab300")) ? null : ic74.get("aab300").toString());
        transferIc74.setAaz159(ValidateUtil.isEmpty(ic74.get("aaz159")) ? null : ic74.get("aaz159").toString());
        transferIc74.setAae732(ValidateUtil.isEmpty(ic74.get("aae732")) ? null : ic74.get("aae732").toString());
        transferIc74.setAae013(ValidateUtil.isEmpty(ic74.get("aae013")) ? null : ic74.get("aae013").toString());
        transferIc74.setAae011(this.transferPersonInfo.getAae011());
        transferIc74.setAae036(new BigDecimal(aae036));
        transferIc74.setAab359(this.transferPersonInfo.getAab359());
        transferIc74.setAac306(this.aac306);
        transferIc74.setAaz002(this.aaz002);


        ArrayList<TransferIc75> listIc75 = new ArrayList<>();

        Sequence sequence_aaz652 = new Sequence();
        sequence_aaz652.setName("aaz652");
        Long aaz652 =  Long.valueOf(sequenceService.nextSequence(sequence_aaz652)+"000");

        for (InformationDetailInfo informationDetailInfo : this.informationDetailInfos) {
            TransferIc75 transferIc75 = new TransferIc75();
            Map ic75 = BeanUtil.beanToMap(informationDetailInfo);

            transferIc75.setAaz635(new BigDecimal(aaz652.toString()));
            transferIc75.setAaz341(ValidateUtil.isEmpty(ic74.get("aaz341")) ? null : ic74.get("aaz341").toString());
            transferIc75.setAab301(ValidateUtil.isEmpty(ic75.get("aab301")) ? null : ic75.get("aab301").toString());
            transferIc75.setAac319(ValidateUtil.isEmpty(ic75.get("aac319")) ? null : ic75.get("aac319").toString());
            transferIc75.setAac001(ValidateUtil.isEmpty(ic75.get("aac001")) ? null : ic75.get("aac001").toString());
            transferIc75.setAae001(ValidateUtil.isEmpty(ic75.get("aae001")) ? null : new BigDecimal(ic75.get("aae001").toString()));
            transferIc75.setAae041(ValidateUtil.isEmpty(ic75.get("aae041")) ? null : new BigDecimal(ic75.get("aae041").toString()));
            transferIc75.setAae042(ValidateUtil.isEmpty(ic75.get("aae042")) ? null : new BigDecimal(ic75.get("aae042").toString()));
            transferIc75.setAae202(ValidateUtil.isEmpty(ic75.get("aae202")) ? null : new BigDecimal(ic75.get("aae202").toString()));
            transferIc75.setAaz159(ValidateUtil.isEmpty(ic75.get("aaz159")) ? null : ic75.get("aaz159").toString());
            transferIc75.setAaz086(ValidateUtil.isEmpty(ic74.get("aaz086")) ? null : new BigDecimal(ic74.get("aaz086").toString()));
            transferIc75.setAae013(ValidateUtil.isEmpty(ic75.get("aae013")) ? null : ic75.get("aae013").toString());
            transferIc75.setAac306(this.aac306);
            transferIc75.setAae011(this.transferPersonInfo.getAae011());
            transferIc75.setAae036(new BigDecimal(aae036));
            transferIc75.setAab359(this.transferPersonInfo.getAab359());
            transferIc75.setAaz002(this.aaz002);
            listIc75.add(transferIc75);
            aaz652++;

        }


        transferIc74Service.save(transferIc74);

        transferIc75Service.saveBatch(listIc75);


        return null;
    }





}






